/** Utility function that generates a texture with transparency based on a certain colour value 
 @remarks 
 	The generated texture will either have full opacity or full transparency values 
 @param filename 
 	The name of the image file this texture will be based on, residing in resGroup 
 @param keyCol 
 	The colour value which should cause transparency (alpha component is ignored) 
 @param resGroup 
 	The resource group the base image file belongs and the generated texture will belong to 
 @param prefix 
 	The generated texture will be accessible via the name prefix+filename 
 @param numMipmaps 
 	Usually you leave that on default, but if you never intend to scale the texture, you can set it to 0
 @param threshold 
 	If the difference between the pixel colour of the image and keyCol is less than this, it gets 
 	transparent. It should be between 0 and 1. The default value is less than (1 / 256), which means 
 	that for an 8 Bit channels input file, only the EXACT keyCol gets transparent. 
 @return 
 	Returns the name of the texture resource the generated texture can be addressed by (is prefix+filename) 
 */ 

#include "Ogre.h"





Ogre::String loadChromaKeyedTexture(const Ogre::ColourValue& usrCol = Ogre::ColourValue::Black, 
 		const Ogre::ColourValue& keyCol = Ogre::ColourValue::Black, 
		const Ogre::uint width = 100,
		const Ogre::uint height = 100,
 		const Ogre::String& resGroup = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, 
 		const Ogre::String& prefix = "ck_",
 		int numMipmaps = Ogre::MIP_DEFAULT,
		float threshold = 1.0f) {


	//using namespace Ogre; 
 	using std::fabs; 
 	// Since Ogre 1.6 Shoggoth, the OGRE_ALLOC_T memory macro must be used:
	Ogre::uchar* pixelData = OGRE_ALLOC_T (Ogre::uchar, Ogre::PixelUtil::getMemorySize (width, height, 1, Ogre::PF_A8R8G8B8), Ogre::MEMCATEGORY_GENERAL);
	Ogre::ulong pxDataIndex = 0, pxDataIndexStep = Ogre::PixelUtil::getNumElemBytes (Ogre::PF_A8R8G8B8); 
 
	for(Ogre::uint y = 0; y < height; ++y) 
 	{ 
 		for(Ogre::uint x = 0; x < width; ++x) 
 		{ 
			Ogre::ColourValue pixCol = usrCol; 
 			Ogre::ColourValue diffCol = pixCol - keyCol; 
 			pixCol.a = ( (fabs(diffCol.r)<=threshold) && (fabs(diffCol.g)<=threshold) && (fabs(diffCol.b)<=threshold) ) 
 				? 0 : 1; 
 			Ogre::PixelUtil::packColour (pixCol, Ogre::PF_A8R8G8B8, static_cast<void*> (pixelData + pxDataIndex) ); 
 			pxDataIndex += pxDataIndexStep; 
 		} 
 	} 


 	Ogre::Image chromaKeyedImg;
 	chromaKeyedImg.loadDynamicImage (pixelData, width, height, 1, Ogre::PF_A8R8G8B8, true); 
	Ogre::String resName = prefix;
 	// You could save the chroma keyed image at this point for caching:
 	// chromaKeyedImg.save(resName); 
	Ogre::TextureManager::getSingleton ().loadImage( resName , resGroup, chromaKeyedImg, Ogre::TEX_TYPE_2D, numMipmaps );
 	return resName;
 }


